package com.chat.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.chat.vo.TokenVo;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
@Service
public class Util {
//    public static Map ObjectToMap(Object object){
//        Map map=new HashMap();
//        Field[] fields = object.getClass().getDeclaredFields();
////        for (Object o : object){
////
////        }
//        System.out.println(fields);
//        return map;
//    }
    private static final Algorithm SING = Algorithm.HMAC256("ccc1122");
        /**
         * 生成token
         */
    public static TokenVo getToken(Map<String,Object> map){
        Calendar instance = Calendar.getInstance();
        //默认7天过期
        instance.add(Calendar.DATE,7);
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k,v)->{
            System.out.println(k);
            System.out.println(v);
            builder.withClaim(k, v.toString());
        });
//        builder.withClaim("user","true");
//            builder.withClaim("a","v");
//        newMap.forEach((k,v)->{
//            System.out.println(k);
//            System.out.println(v);
//            builder.withClaim(k,v);
//        });
        String token = builder.withExpiresAt(instance.getTime()).sign(SING);
        TokenVo tokenvo = new TokenVo(token,true);
        return tokenvo;
    }

    /**
     * 验证token合法性
     * @Return TokenVo(Object data; Boolean isSucceed);
     */
    public static TokenVo verifyToken(String token){
        TokenVo tokenvo = new TokenVo("失败",false);
        DecodedJWT jwt=null;
        try {
            JWTVerifier verifier=JWT.require(SING).build();
            jwt=verifier.verify(token);
        }catch (Exception e){
            System.out.println(e.getMessage());
            System.out.println("解析编码异常");
        }
        if(jwt==null){
            return tokenvo;
        }
        tokenvo.data= jwt.getClaims();
        tokenvo.isSucceed=true;
        return tokenvo;
//        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
